package com.example.mahao_final.UI

import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mahao_final.R
import com.example.mahao_final.adapter.MyBlogAdapter
import com.example.mahao_final.database.BlogDatabase
import com.example.mahao_final.entity.Blog
import com.example.mahao_final.entity.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MyBolgFragment : Fragment(R.layout.fragment_blog) {

    private lateinit var rvBlogList: RecyclerView
    private lateinit var myBlogAdapter: MyBlogAdapter
    private val blogDao by lazy { BlogDatabase.getDatabase(requireContext()).blogDao() }

    // 使用 ActivityResultContracts 来处理编辑结果
    private val editBlogResultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // 从返回的 Intent 获取更新的博客 ID
                val blogId = result.data?.getLongExtra("BLOG_ID", 0) ?: 0L
                if (blogId != 0L) {
                    // 在编辑博客后刷新数据
                    loadUserBlogs()
                }
            }
        }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        rvBlogList = view.findViewById(R.id.rv_blog_list)

        // 设置 RecyclerView
        rvBlogList.layoutManager = LinearLayoutManager(requireContext())

        // 创建适配器，并设置点击回调
        myBlogAdapter = MyBlogAdapter(
            blogs = emptyList(),
            context = requireContext(),  // 传递当前 Fragment 的上下文
            onBlogClick = { blog ->
                // 点击事件回调，启动新的 Activity 显示博客的详细信息
                showBlogDetails(blog)
            },
            onEditClick = { blog ->
                // 点击编辑按钮，跳转到编辑页面
                editBlog(blog)
            },
            onDeleteClick = { blog ->
                // 点击删除按钮，弹出二次确认框
                confirmDeleteBlog(blog)
            }
        )

        rvBlogList.adapter = myBlogAdapter

        // 加载当前用户的博客数据
        loadUserBlogs()
    }

    private fun loadUserBlogs() {
        val currentUser = getCurrentUser()

        lifecycleScope.launch {
            val blogs = if (currentUser.username == "admin") {
                // 如果是 admin 用户，查询所有博客
                blogDao.getAllBlogs()
            } else {
                // 否则查询当前用户的博客
                blogDao.getBlogsByUsername(currentUser.nickname)
            }

            myBlogAdapter.updateList(blogs)  // 更新 RecyclerView 数据
        }
    }

    private fun getCurrentUser(): User {
        val sharedPreferences = requireContext().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE)
        val username = sharedPreferences.getString("username", "") ?: ""
        val nickname = sharedPreferences.getString("nickname", "Unknown") ?: ""
        val password = sharedPreferences.getString("password", "") ?: ""  // 获取密码

        return User(username = username, nickname = nickname, password = password)  // 提供密码字段
    }

    // 处理点击博客跳转到博客详情的逻辑
    private fun showBlogDetails(blog: Blog) {
        // 启动 BlogDetailActivity 并传递博客的 ID
        val intent = Intent(requireContext(), BlogDetailActivity::class.java)
        intent.putExtra("BLOG_ID", blog.id)  // 传递博客的 ID
        startActivity(intent)
    }

    // 编辑博客逻辑
    private fun editBlog(blog: Blog) {
        // 启动编辑博客界面，传递博客信息
        val intent = Intent(requireContext(), BlogEditActivity::class.java)
        intent.putExtra("BLOG_ID", blog.id)
        editBlogResultLauncher.launch(intent)  // 使用编辑结果回调
    }

    private fun confirmDeleteBlog(blog: Blog?) {
        // 先检查 blog 是否为 null
        blog?.let {
            context?.let { context ->
                val alertDialog = AlertDialog.Builder(context)
                    .setTitle("确认删除")
                    .setMessage("你确定要删除这篇博客吗？")
                    .setPositiveButton("确定") { _, _ ->
                        // 使用协程进行数据库操作
                        lifecycleScope.launch {
                            // 在 IO 线程执行数据库删除操作
                            withContext(Dispatchers.IO) {
                                blogDao.deleteBlogById(it.id)
                            }

                            // 删除完成后刷新数据，确保 UI 操作在主线程
                            loadUserBlogs()

                            // 删除成功后的提示
                            Toast.makeText(context, "博客删除成功!", Toast.LENGTH_SHORT).show()
                        }
                    }
                    .setNegativeButton("取消", null)
                    .create()

                alertDialog.show()
            }
        } ?: run {
            // 处理 blog 为 null 的情况，避免发生 NullPointerException
            Toast.makeText(requireContext(), "无法删除博客，博客数据为空", Toast.LENGTH_SHORT).show()
        }
    }


}
